#include "server.h"
#include "messtran.h"

Server::Server(QObject *parent, quint16 uport) : QObject(parent)
{
    server = new QTcpServer();
    server->listen(QHostAddress::Any,uport);
    std::cout<<"uport: "<<uport<<std::endl;
    connect(server,SIGNAL(newConnection()),this,SLOT(acceptConnection()));

}

void Server::acceptConnection(){

    QTcpSocket *client = server->nextPendingConnection();
    std::cout<<"New connect: "<<client->peerAddress().toString().toStdString()<<' '<<client->peerPort()<<std::endl;
    connect(client,SIGNAL(readyRead()),this,SLOT(readClient()));
    connect(client,SIGNAL(disconnected()),this,SLOT(recvDiscon()));
    clients.insert(client);
    if(client->waitForConnected()){
        for(QSet<QString>::iterator it = users.begin();it!=users.end();it++){

            client->write(conTran("a",*it).toLocal8Bit());
            client->flush();
        }
    }

}

void Server::readClient(){
    QTcpSocket *cur = dynamic_cast<QTcpSocket*>(sender());
    if(cur==0) return;
    QByteArray mess = cur->readAll();
    std::cout<<mess.toStdString()<<std::endl;
    QStringList qsl = QString(mess).split('|',QString::SkipEmptyParts);
    for(int i=0;i<qsl.size();i++){
        QString curStr = qsl[i];
        QStringList qsl2 = curStr.split('&',QString::SkipEmptyParts);

        if(qsl2[0]=="c"){
            if(qsl2[1]=="a"){
                users.insert(qsl2[2]);
                userMap.insert(cur,qsl2[2]);
            }
            else if(qsl2[1]=="r"){
                //remove users parts
            }
        }


    }

    sendAll(mess);


    //    if(qsl.size()>1){
    //        userMap.insert(cur,qsl.at(1));
    //        for(int i=1;i<qsl.size();i++){
    //            users.insert(qsl.at(i));
    //        }
    //    }

    //    for(QSet<QTcpSocket*>::iterator it = clients.begin();it!=clients.end();it++){
    //        QTcpSocket* tmp = *it;
    //        if(tmp->isOpen()){
    //            tmp->write(mess);
    //        }
    //    }


    //    for(std::vector< QTcpSocket* >::iterator it = clients.begin();it!=clients.end();it++){
    //        cur = *it;
    //        QString tmp = cur->readAll();
    //        if(tmp.isEmpty()) continue;
    //        std::cout<<tmp.toStdString()<<std::endl;
    //        mess = tmp;
    //        break;
    //    }
    //    if(mess[0]=='&'){
    //        users.push_back(mess);
    //    }

    //    for(std::vector< QTcpSocket* >::iterator it = clients.begin();it!=clients.end();it++){
    //        cur = *it;

    //        cur->write(mess.toLocal8Bit());


    //    }
}

void Server::recvDiscon(){
    QTcpSocket *cur = dynamic_cast<QTcpSocket*>(sender());
    if(cur==0) return;
    clients.remove(cur);
    users.remove(userMap[cur]);
    if(cur->state()!=QAbstractSocket::UnconnectedState){
        if(cur->waitForDisconnected()){
            cur->close();
        }
    }
    else cur->close();

    std::cout<<userMap[cur].toStdString()<<" gone"<<std::endl;
    std::cout<<conTran("r",userMap[cur]).toStdString()<<std::endl;
    sendAll(conTran("r",userMap[cur]));

}

void Server::sendAll(QString inf){
    for(QSet<QTcpSocket*>::iterator it = clients.begin();it!=clients.end();it++){
        QTcpSocket* tmp = *it;
        if(tmp->isOpen()){
            tmp->write(inf.toLocal8Bit());
            tmp->flush();
        }
    }
}
